package pdm.yamba.service;

import pdm.yamba.MainApplication;
import pdm.yamba.TimelineActivity;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class TimelinePullService extends Service {
	private HandlerThread _worker;
	private Handler _uiHandler;
	private Handler _workerHandler;
	private MainApplication application;
	
	@Override
	public void onCreate() 
	{
		super.onCreate();
		Log.v("Yamba", "TimelinePullService.onCreate() on thread " + Thread.currentThread().getId());
		
		_worker = new HandlerThread("TimelinePullService worker thread");
		_worker.start();
		
		_uiHandler = new Handler();
		_workerHandler = new Handler(_worker.getLooper(), new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) 
			{
				Log.v("Yamba", "handleMessage() on thread " + Thread.currentThread().getName());
				
				@SuppressWarnings("unused")
				Bundle payload = msg.getData();
				
				application = (MainApplication) getApplication();
				
				if(application.isOnline())
				{
					application.RefreshStatusViaService();
					
					_uiHandler.post(new Runnable() {
			
						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "TimeLine Updated", Toast.LENGTH_LONG).show();
							
						}
					});
				}
				return true;
			}
		});
	}

	@Override
	public int onStartCommand(final Intent intent, int flags, int startId) 
	{
		Log.v("Yamba", "TimelinePullService.onStartCommand() on thread " + Thread.currentThread().getId());
		
		Message msg = Message.obtain();
		msg.setData(intent.getExtras());
		_workerHandler.sendMessage(msg);
		
		return 0; // We will revisit this.
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
}
